--饭卡保管
local fankabaoguan = fk.CreateSkill {
    name = "mcdh_fankabaoguan"
}

local U = require "packages/utility/utility"
local lib = require "packages/mcdh/lib"

fankabaoguan:addEffect(fk.EventPhaseStart,{
    can_trigger = function(self, event, target, player, data)
        return target == player and player:hasSkill(self) and player.phase == Player.Play and
                table.find(player.room:getOtherPlayers(player, false), function(p) return not p:isKongcheng() end)
    end,
    on_cost = function(self, event, target, player, data)
        local room = player.room
        local targets = table.filter(room:getOtherPlayers(player, false), function(p)
            return not p:isKongcheng() end)
        local result = room:askToChoosePlayers(player,{targets= targets,min_num=1,max_num=3,skill_name=self.name,prompt="#mcdh_fankabaoguan-ask"})
        if #result > 0 then
            event:setCostData(self,result)
            return true
        end
    end,
    on_use = function(self, event, target, player, data)
        local room = player.room
        local targets = event:getCostData(self)
        room:sortByAction(targets)
        room:setPlayerMark(player, "@mcdh_fankabaoguan-turn", table.map(targets,Util.IdMapper))
        for _, p in ipairs(targets) do
            if player.dead then return end
            if not p.dead and not p:isKongcheng() then
                local c = room:askForCardChosen(player, p, "h", self.name)
                room:obtainCard(player, c, false, fk.ReasonPrey)
            end
        end
    end,
})

fankabaoguan:addEffect(fk.EventPhaseStart,{
    is_delay_effect = true,
    can_trigger = function(self, event, target, player, data)
        return target == player and player:getMark("mcdh_fankabaoguan-turn") ~= 0 and player.phase == Player.Finish
    end,
    on_cost = function(self, event, target, player, data)
        return true
    end,
    on_use = function(self, event, target, player, data)
        local room = player.room
        local num = 3 - player:getHandcardNum()
        if num > 0 then
            player:drawCards(num, self.name)
        end
        for _, pid in ipairs(player:getMark("mcdh_fankabaoguan-turn")) do
            if player:isKongcheng() then break end
            local p = room:getPlayerById(pid)
            if not p.dead and p ~= player then
                local card = room:askForCard(player, 1, 1, true, self.name, false, ".", "#mcdh_fankabaoguan-give::"..pid)
                if #card > 0 then
                    room:obtainCard(p, card[1], false, fk.ReasonGive)
                end
            end
        end
    end,
})


Fk:loadTranslationTable {
    ["mcdh_fankabaoguan"] = "饭卡保管",
    [":mcdh_fankabaoguan"] = "出牌阶段开始时，你可以获得至多三名其他角色各一张手牌，若如此做，结束阶段你将手牌摸至三张，然后交给这些角色各一张牌",
    ["#mcdh_fankabaoguan-ask"] = "是否发动“饭卡保管”，获得1-3名角色各一张手牌？",
    ["#mcdh_fankabaoguan-give"] = "饭卡保管：交给 %dest 一张牌"
}

return fankabaoguan